package com.boarsoft.web.websocket;

import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.boarsoft.common.util.JsonUtil;

/**
 * 
 * @author Mac_J
 *
 */
@ServerEndpoint("/websocket")
public class WebsocketEndpoint {
	private static final Logger log = LoggerFactory.getLogger(WebsocketEndpoint.class);

	/** */
	protected static final Map<String, Session> sessionMap = new ConcurrentHashMap<String, Session>();
	/** 注册的监听器， key是消息类型 */
	protected static final Map<String, Set<WebsocketListener>> listenerMap = new HashMap<String, Set<WebsocketListener>>();

	public static Session getSession(String sessionId) {
		return sessionMap.get(sessionId);
	}

	@OnOpen
	public void onOpen(Session session) {
		String sid = session.getId();
		sessionMap.put(sid, session);
		log.info("Incoming websocket session {}, {} sessions now", sid, sessionMap.size());
		for (Set<WebsocketListener> elSet : listenerMap.values()) {
			for (WebsocketListener el : elSet) {
				el.onOpen(session);
			}
		}
	}

	/**
	 * 连接关闭调用的方法
	 */
	@OnClose
	public void onClose(Session session) {
		String sid = session.getId();
		log.info("Websocket session {} is closed, {} sessions remain.", sid, sessionMap.size());
		sessionMap.remove(sid);
		for (Set<WebsocketListener> elSet : listenerMap.values()) {
			for (WebsocketListener el : elSet) {
				el.onClose(session);
			}
		}
	}

	/**
	 * 收到客户端消息后调用的方法
	 * 
	 * @param msg
	 *            客户端发送过来的消息
	 * @param session
	 *            可选的参数
	 */
	@OnMessage
	public void onMessage(String msg, Session session) {
		String from = session.getId();
		log.info("Received websocket message {} from session {}", msg, from);
		WebsocketMessage m = JsonUtil.parseObject(msg, WebsocketMessage.class);
		String g = m.getGroup();
		if (listenerMap.containsKey(g)) {
			Set<WebsocketListener> elSet = listenerMap.get(g);
			for (WebsocketListener el : elSet) {
				el.onMessage(m, session);
			}
		}
	}

	@OnError
	public void onError(Session session, Throwable error) {
		String sid = session.getId();
		log.error("Error on websocket session {}", sid, error);
		try {
			session.close();
		} catch (Exception e) {
			log.error("Error on close websocket session {}", sid, e);
		} finally {
			sessionMap.remove(sid);
		}
		for (Set<WebsocketListener> elSet : listenerMap.values()) {
			for (WebsocketListener el : elSet) {
				el.onError(session, error);
			}
		}
	}

	public static void addListener(String group, WebsocketListener wel) {
		Set<WebsocketListener> set = listenerMap.get(group);
		if (set == null) {
			synchronized (listenerMap) {
				set = listenerMap.get(group);
				if (set == null) {
					set = new HashSet<WebsocketListener>();
					listenerMap.put(group, set);
				}
			}
		}
		set.add(wel);
	}

	public static int send(WebsocketMessage m, String sid) {
		Session s = sessionMap.get(sid);
		if (s == null) {
			log.warn("Websocket session of {} is null", sid, m);
			return -1;
		}
		return send(m, s);
	}

	public static int send(WebsocketMessage m, Session s) {
		try {
			switch (m.getType()) {
			case WebsocketMessage.TYPE_TEXT:
				synchronized (s) {
					s.getBasicRemote().sendText(JsonUtil.from(m));
				}
				break;
			case WebsocketMessage.TYPE_BINARY:
				// TODO
				// s.getBasicRemote().sendObject(m.getData());
				break;
			case WebsocketMessage.TYPE_OBJECT:
				// TODO
				// s.getBasicRemote().sendObject(m.getData());
				break;
			}
			return 0;
		} catch (IOException e) {
			log.error("Error on send websocket message {} to {}", m, s.getId(), e);
			return -1;
		}
	}

	public static Map<String, Session> getSessionMap() {
		return sessionMap;
	}
}
